package com.motu.monstercity.server.game.logichandler;

import com.google.protobuf.InvalidProtocolBufferException;
import com.motu.monstercity.module.common.network.RequestParam;
import com.motu.monstercity.module.common.servermanager.ServerManager;
import com.motu.monstercity.protocol.Common;
import com.motu.monstercity.protocol.CsGameUnionscuffle.*;
import com.motu.monstercity.server.game.base.AllParam;
import com.motu.monstercity.server.game.base.CommonUtils;
import com.motu.monstercity.server.game.base.LockKey;
import com.motu.monstercity.server.game.base.ProtoDataUtils;
import com.motu.monstercity.server.game.commondata.act.Act;
import com.motu.monstercity.server.game.commondata.act.ActConstant;
import com.motu.monstercity.server.game.commondata.bag.ItemId;
import com.motu.monstercity.server.game.commondata.bag.ItemModel;
import com.motu.monstercity.server.game.commondata.rank.RankConstant;
import com.motu.monstercity.server.game.commondata.rank.RankReward;
import com.motu.monstercity.server.game.commondata.shop.Shop;
import com.motu.monstercity.server.game.commondata.shop.ShopConstant;
import com.motu.monstercity.server.game.commondata.union.UnionScuffleGift;
import com.motu.monstercity.server.game.commondata.union.UnionScufflePass;
import com.motu.monstercity.server.game.log.LogType;
import com.motu.monstercity.server.game.logic.*;
import com.motu.monstercity.server.game.userdata.*;
import com.motu.vertx.module.utility.main.MainService;
import com.motu.vertx.module.utility.toolset.ErrorWord;
import com.motu.vertx.module.utility.toolset.TimeUtils;
import com.motu.vertx.module.utility.toolset.Tool;
import io.vertx.core.json.JsonArray;
import io.vertx.core.shareddata.Lock;

import java.util.Comparator;
import java.util.List;
import java.util.UUID;

/**
 * 联盟乱斗协议
 */
public class UnionscuffleHandler {

    // CMD_GAME_UNIONSCUFFLE_INFO = 73401; // 乱斗信息
    public static Object CMD_GAME_UNIONSCUFFLE_INFO(RequestParam clientParam) throws Exception {
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        if (!FunctionManager.isFunctionClientOpen(FunctionManager.FUNCTION_ID_UNION_SCUFFLE, userInfo.getServerId())) {
            return ErrorWord.MODULE_LOCKED;
        }
        CSGameUnionscuffleInfoRequest request = CSGameUnionscuffleInfoRequest.parseFrom(clientParam.getData());
//        long actId = request.getActId();
//        Act act = ActManager.getAct(actId);
//        if (act == null || !act.isStart(userInfo.getServerId()) || act.getType() != ActConstant.ACT_TYPE_UNION_SCUFFLE) {
//            return ErrorWord.NOT_DATA; // 活动未开始
//        }
        if (!UnionScuffleManager.isDuringGame() && !UnionScuffleManager.isRewardTime()) {
            return ErrorWord.NOT_DATA; // 活动未开始
        }
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        if (userUnion.getUnionId() == 0) {
            return ErrorWord.MODULE_LOCKED; // 暂未开放
        }
        long memberCount = UnionManager.getUnionMemberNum(userUnion.getUnionId());
        if (memberCount < AllParam.UNION_SCUFFLE_MEMBER_LIMIT) {
            return ErrorWord.MODULE_LOCKED; // 人员数量不满足
        }
        CSGameUnionscuffleInfoResponse.Builder response = CSGameUnionscuffleInfoResponse.newBuilder();
        Common.PBUserData.Builder pbUserData = response.getUserBuilder();
        if (UnionScuffleManager.isDuringGame()) {
            UserUnionScuffleInfoWeek userUnionScuffleInfo = UnionScuffleManager.getUserUnionScuffleInfo(clientParam.getUserId());
            ProtoDataUtils.updatePBUserData(pbUserData, userUnionScuffleInfo);
            if (userUnionScuffleInfo.getEnemyUnionId() != 0) {
                UserUnionScuffleWeek userUnionScuffle = UnionScuffleManager.getUserUnionScuffle(userId, userUnionScuffleInfo.getEnemyUnionId());
                if (userUnionScuffle != null) {
                    ProtoDataUtils.updatePBUserData(pbUserData, userUnionScuffle, true);
                    JsonArray memberList = userUnionScuffle.getChooseListArray();
                    for (int i = 0; i < memberList.size(); i++) {
                        long memberId = memberList.getLong(i);
                        UserUnionScuffleMemberWeek member = UnionScuffleManager.getUserUnionScuffleMember(userId, userUnionScuffleInfo.getEnemyUnionId(), memberId);
                        if (null != member) {
                            UnionScuffleManager.updateMemberInfo(pbUserData, member, userUnionScuffle);
                        }
                    }
                    List<UserUnionScuffleMemberWeek> allMemberList = UnionScuffleManager.getUserUnionScuffleMemberList(userId, userUnionScuffle.getEnemyUnionId());
                    allMemberList.sort(Comparator.comparing(UserUnionScuffleMemberWeek::getPower).reversed());
                    allMemberList = allMemberList.subList(0, Math.min(memberList.size(), 5));
                    for (UserUnionScuffleMemberWeek member : allMemberList) {
                        Common.PBUserUnionScuffleMember.Builder memberBuilder = UnionScuffleManager.takeMemberInfo(member, userUnionScuffle);
                        response.addTopMemberList(memberBuilder);
                    }
                    long myPower = UnionScuffleManager.countPower(userUnionScuffle);
                    response.setMyPower(myPower);
                }
            }
            List<UserUnionScuffleGiftWeek> giftList = UnionScuffleManager.getUserUnionScuffleGiftList(userInfo.getId());
            for (UserUnionScuffleGiftWeek gift : giftList) {
                ProtoDataUtils.updatePBUserData(pbUserData, gift, true);
            }
        }
        List<UserUnionScuffleShopWeek> shopList = UnionScuffleManager.getUserUnionScuffleShopList(userInfo.getId());
        for (UserUnionScuffleShopWeek shop : shopList) {
            ProtoDataUtils.updatePBUserData(pbUserData, shop, true);
        }
        int actGroup = ServerManager.getWarZoneId(userInfo.getServerId());
        JsonArray serverIdList = ServerManager.getServerIdListByWarZone(actGroup);
        if (serverIdList != null) {
            for (int i = 0; i < serverIdList.size(); i++) {
                int serverId = serverIdList.getInteger(i);
                response.addJoinServerList(serverId);
            }
        }
        return response;
    }

    // CMD_GAME_UNIONSCUFFLE_MATCH = 73402; // 乱斗匹配
    public static Object CMD_GAME_UNIONSCUFFLE_MATCH(RequestParam clientParam) throws Exception {
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        if (!FunctionManager.isFunctionClientOpen(FunctionManager.FUNCTION_ID_UNION_SCUFFLE, userInfo.getServerId())) {
            return ErrorWord.MODULE_LOCKED;
        }
        CSGameUnionscuffleMatchRequest request = CSGameUnionscuffleMatchRequest.parseFrom(clientParam.getData());
//        long actId = request.getActId();
//        Act act = ActManager.getAct(actId);
//        if (act == null || !act.isGetRewardTime(userInfo.getServerId()) || act.getType() != ActConstant.ACT_TYPE_UNION_SCUFFLE) {
//            return ErrorWord.NOT_DATA; // 活动未开始
//        }
        if (!UnionScuffleManager.isDuringGame()) {
            return ErrorWord.NOT_DATA; // 活动未开始
        }
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        if (userUnion.getUnionId() == 0) {
            return ErrorWord.MODULE_LOCKED; // 暂未开放
        }
        long memberCount = UnionManager.getUnionMemberNum(userUnion.getUnionId());
        if (memberCount < AllParam.UNION_SCUFFLE_MEMBER_LIMIT) {
            return ErrorWord.MODULE_LOCKED; // 人员数量不满足
        }
//        long curTime = TimeUtils.getCurTime();
//        if (!UnionScuffleManager.isMatchTime(curTime)) {
//            return ErrorWord.WRONG_STATUS;
//        }
        UserUnionScuffleInfoWeek userUnionScuffleInfo = UnionScuffleManager.getUserUnionScuffleInfo(clientParam.getUserId());
        if (userUnionScuffleInfo.getEnemyUnionId() > 0) {
            return ErrorWord.REPEATED_OPERATION;
        }
        long unionId = userUnion.getUnionId();
        long targetUnionId = request.getTargetUnionId();
        if (targetUnionId == unionId) {
            return ErrorWord.INVALID_OPERATION; // 不能匹配自己
        }
        CSGameUnionscuffleMatchResponse.Builder response = CSGameUnionscuffleMatchResponse.newBuilder();
        Common.PBUserData.Builder pbUserData = response.getUserBuilder();
        int matchType = targetUnionId > 0 ? UserUnionScuffle.MATCH_TYPE_CHALLENGE : UserUnionScuffle.MATCH_TYPE_RANDOM;
        if (targetUnionId == 0) {
            int energy = userUnionScuffleInfo.getEnergy();
            if (energy <= 0) {
                if (!BagManager.checkNeedItemNum(userInfo, ItemId.SCUFFLE_TOKEN, 1)) {
                    return ErrorWord.ITEM_LACK;
                }
            }
            targetUnionId = UnionScuffleManager.matchBattle(userInfo, unionId);
            if (targetUnionId == 0) {
                return ErrorWord.NOT_DATA_1;
            }
            if (energy > 0) { // 消耗体力
                userUnionScuffleInfo.subEnergy(userInfo, 1, LogType.UNION_SCUFFLE_MATCH);
            } else { // 消耗乱斗令
                RewardManager.subReward(userInfo, ItemId.SCUFFLE_TOKEN, 1, pbUserData, LogType.UNION_SCUFFLE_MATCH);
            }
        } else { // 消耗挑战书
            if (!BagManager.checkNeedItemNum(userInfo, ItemId.SCUFFLE_CHALLENGE_LETTER, 1)) {
                return ErrorWord.ITEM_LACK;
            }
            RewardManager.subReward(userInfo, ItemId.SCUFFLE_CHALLENGE_LETTER, 1, pbUserData, LogType.UNION_SCUFFLE_MATCH);
        }
        userUnionScuffleInfo.putEnemyUnionId(targetUnionId);
        userUnionScuffleInfo.update();
        ProtoDataUtils.updatePBUserData(pbUserData, userUnionScuffleInfo);
        UserUnionScuffleWeek userUnionScuffle = UnionScuffleManager.createUnionBattle(userInfo, targetUnionId, matchType);
        List<UserUnionScuffleMemberWeek> memberList = UnionScuffleManager.refreshMemberList(userUnionScuffle);
//        int serverGroup = ServerManager.getServerActGroup(userInfo.getServerId());
        for (UserUnionScuffleMemberWeek member : memberList) {
            UnionScuffleManager.updateMemberInfo(pbUserData, member, userUnionScuffle);
//            ProtoDataUtils.updatePBUserData(pbUserData, member);
        }
        List<UserUnionScuffleMemberWeek> allMemberList = UnionScuffleManager.getUserUnionScuffleMemberList(userId, targetUnionId);
        allMemberList.sort(Comparator.comparing(UserUnionScuffleMemberWeek::getPower).reversed());
        allMemberList = allMemberList.subList(0, Math.min(memberList.size(), 5));
        for (UserUnionScuffleMemberWeek member : allMemberList) {
            Common.PBUserUnionScuffleMember.Builder memberBuilder = UnionScuffleManager.takeMemberInfo(member, userUnionScuffle);
            response.addTopMemberList(memberBuilder);
        }
        ProtoDataUtils.updatePBUserData(pbUserData, userUnionScuffle, true);

        return response;
    }

    // CMD_GAME_UNIONSCUFFLE_CHOOSE_BUFF = 73403; // 选择临时加成
    public static Object CMD_GAME_UNIONSCUFFLE_CHOOSE_BUFF(RequestParam clientParam) throws Exception {
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        if (!FunctionManager.isFunctionClientOpen(FunctionManager.FUNCTION_ID_UNION_SCUFFLE, userInfo.getServerId())) {
            return ErrorWord.MODULE_LOCKED;
        }
        CSGameUnionscuffleChooseBuffRequest request = CSGameUnionscuffleChooseBuffRequest.parseFrom(clientParam.getData());
//        long actId = request.getActId();
//        Act act = ActManager.getAct(actId);
//        if (act == null || !act.isGetRewardTime(userInfo.getServerId()) || act.getType() != ActConstant.ACT_TYPE_UNION_SCUFFLE) {
//            return ErrorWord.NOT_DATA; // 活动未开始
//        }
        if (!UnionScuffleManager.isDuringGame()) {
            return ErrorWord.NOT_DATA;
        }
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        if (userUnion.getUnionId() == 0) {
            return ErrorWord.MODULE_LOCKED; // 暂未开放
        }
        long memberCount = UnionManager.getUnionMemberNum(userUnion.getUnionId());
        if (memberCount < AllParam.UNION_SCUFFLE_MEMBER_LIMIT) {
            return ErrorWord.MODULE_LOCKED; // 人员数量不满足
        }
        UserUnionScuffleInfoWeek userUnionScuffleInfo = UnionScuffleManager.getUserUnionScuffleInfo(userId);
        if (userUnionScuffleInfo.getEnemyUnionId() <= 0) {
            return ErrorWord.INVALID_OPERATION; // 未匹配战斗
        }
        UserUnionScuffleWeek userUnionScuffle = UnionScuffleManager.getUserUnionScuffle(userId, userUnionScuffleInfo.getEnemyUnionId());
        if (userUnionScuffle == null) {
            return ErrorWord.NOT_DATA;
        }
        if (userUnionScuffle.getAddPerType() > 0) {
            return ErrorWord.ALREADY_MAX; // 已选择战斗加成
        }
        int type = request.getType();
        if (type <= 0 || type > 3) {
            return ErrorWord.BAD_PARAM;
        }
        CSGameUnionscuffleChooseBuffResponse.Builder response = CSGameUnionscuffleChooseBuffResponse.newBuilder();
        Common.PBUserData.Builder pbUserData = response.getUserBuilder();
        int cost = AllParam.UNION_SCUFFLE_ADD_PER[(type - 1) * 2 + 1];
        if (cost > 0) {
            if (!BagManager.checkNeedItemNum(userInfo, ItemId.DIAMOND, cost)) {
                return ErrorWord.DIAMOND_LACK;
            }
            RewardManager.subReward(userInfo, ItemId.DIAMOND, cost, pbUserData, LogType.UNION_SCUFFLE_CHOOSE_BUFF);
        }
        userUnionScuffle.putAddPerType(type);
        int addPer = UnionScuffleManager.getAddPerType(type);
        long initHp = (long) (userUnionScuffle.getInitPower() * 2.5 * (10000 + addPer) / 10000);
        userUnionScuffle.putInitHp(initHp);
        userUnionScuffle.putCurHp(initHp);
        userUnionScuffle.update();
        JsonArray memberList = userUnionScuffle.getChooseListArray();
        for (int i = 0; i < memberList.size(); i++) {
            long memberId = memberList.getLong(i);
            UserUnionScuffleMemberWeek member = UnionScuffleManager.getUserUnionScuffleMember(userId, userUnionScuffleInfo.getEnemyUnionId(), memberId);
            if (null != member) {
                UnionScuffleManager.updateMemberInfo(pbUserData, member, userUnionScuffle);
            }
        }
        ProtoDataUtils.updatePBUserData(pbUserData, userUnionScuffle, true);
        response.setMyPower(UnionScuffleManager.countPower(userUnionScuffle));
        return response;
    }

    // CMD_GAME_UNIONSCUFFLE_FIGHT = 73404; // 选择成员战斗并开始战斗
    public static Object CMD_GAME_UNIONSCUFFLE_FIGHT(RequestParam clientParam) throws Exception {
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        if (!FunctionManager.isFunctionClientOpen(FunctionManager.FUNCTION_ID_UNION_SCUFFLE, userInfo.getServerId())) {
            return ErrorWord.MODULE_LOCKED;
        }
        CSGameUnionscuffleFightRequest request = CSGameUnionscuffleFightRequest.parseFrom(clientParam.getData());
//        long actId = request.getActId();
//        Act act = ActManager.getAct(actId);
//        if (act == null || !act.isGetRewardTime(userInfo.getServerId()) || act.getType() != ActConstant.ACT_TYPE_UNION_SCUFFLE) {
//            return ErrorWord.NOT_DATA; // 活动未开始
//        }
        if (!UnionScuffleManager.isDuringGame()) {
            return ErrorWord.NOT_DATA;
        }
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        if (userUnion.getUnionId() == 0) {
            return ErrorWord.MODULE_LOCKED; // 暂未开放
        }
        long memberCount = UnionManager.getUnionMemberNum(userUnion.getUnionId());
        if (memberCount < AllParam.UNION_SCUFFLE_MEMBER_LIMIT) {
            return ErrorWord.MODULE_LOCKED; // 人员数量不满足
        }
        UserUnionScuffleInfoWeek userUnionScuffleInfo = UnionScuffleManager.getUserUnionScuffleInfo(userId);
        long enemyUnionId = userUnionScuffleInfo.getEnemyUnionId();
        if (enemyUnionId == 0) {
            return ErrorWord.NOT_DATA_2; // 未匹配对手
        }
        UserUnionScuffleWeek userUnionScuffle = UnionScuffleManager.getUserUnionScuffle(userId, enemyUnionId);
        if (userUnionScuffle == null) {
            return ErrorWord.NOT_DATA;
        }
        if (userUnionScuffle.getAddPerType() <= 0) {
            return ErrorWord.INVALID_OPERATION;
        }
        if (userUnionScuffle.getCurHp() <= 0) {
            return ErrorWord.WRONG_STATUS; // 战斗已结束
        }
        int actGroup = ServerManager.getWarZoneId(userInfo.getServerId());
        long memberId = request.getMemberId();
        CSGameUnionscuffleFightResponse.Builder response = CSGameUnionscuffleFightResponse.newBuilder();
        Common.PBUserData.Builder pbUserData = response.getUserBuilder();
        Lock lock = null;
        long unionId = userUnion.getUnionId();
        try {
            lock = MainService.getVertLock(LockKey.getUnionScuffleLock(enemyUnionId));
            if (memberId > 0) {
                JsonArray defeatMembersArray = userUnionScuffle.getDefeatedMembersArray();
                if (Tool.isInList(defeatMembersArray, memberId)) {
                    return ErrorWord.REPEATED_OPERATION; // 该成员已被打败
                }
                UserUnionScuffleMemberWeek member = UnionScuffleManager.getUserUnionScuffleMember(userId, userUnionScuffleInfo.getEnemyUnionId(), memberId);
                if (member == null) {
                    return ErrorWord.NOT_DATA_1;
                }
                long myPower = UnionScuffleManager.countPower(userUnionScuffle);
                boolean isWin = UnionScuffleManager.fight(userUnionScuffle, member, response);
                if (isWin) {
                    userUnionScuffleInfo.addBeatNum(1);
                }
                userUnionScuffle.update();
                UnionScuffleManager.subScore(userInfo, unionId, userUnionScuffle, userUnionScuffleInfo, myPower, member.getPower(), userUnionScuffleInfo.getEnemyUnionId());
                long curHp = userUnionScuffle.getCurHp();
                List<UserUnionScuffleMemberWeek> memberList = UnionScuffleManager.refreshMemberList(userUnionScuffle);
                if (curHp > 0 && !memberList.isEmpty()) { // 战斗未结束则继续随机出对手
                    for (UserUnionScuffleMemberWeek userUnionScuffleMember : memberList) {
                        UnionScuffleManager.updateMemberInfo(pbUserData,  userUnionScuffleMember, userUnionScuffle);
//                        ProtoDataUtils.updatePBUserData(pbUserData, userUnionScuffleMember);
                    }
                } else {
                    response.setTotalAddScore(userUnionScuffle.getSubScore());
                    UnionScuffleManager.endBattle(pbUserData, userInfo, userUnionScuffleInfo, userUnionScuffle, userUnion.getUnionId());
                    response.setIsEnd(1);
                }
                UnionScuffleManager.updateAchieve(pbUserData, userInfo, userUnion.getUnionId(), 1);
                ProtoDataUtils.updatePBUserData(pbUserData, userUnionScuffle, true);
                response.setMyPower(UnionScuffleManager.countPower(userUnionScuffle));
            } else { // 一键挑战
                if (userUnionScuffleInfo.getBuyHigh() == 0 && userUnionScuffleInfo.getBuySpecial() == 0) {
                    return ErrorWord.NOT_DATA_3;
                }
                boolean hasFight = false; // 是否战斗过
                List<UserUnionScuffleMemberWeek> memberList = UnionScuffleManager.getUserUnionScuffleMemberList(userId, userUnionScuffleInfo.getEnemyUnionId());
                if (memberList.isEmpty()) {
                    return ErrorWord.ALREADY_MAX;
                }
                while (userUnionScuffle.getCurHp() > 0) {
                    JsonArray defeatMembersArray = userUnionScuffle.getDefeatedMembersArray();
                    long curPower = UnionScuffleManager.countPower(userUnionScuffle);
                    List<UserUnionScuffleMemberWeek> fightList = memberList.stream().filter(m ->
                            !Tool.isInList(defeatMembersArray, m.getMemberId()) && m.getPower() < curPower).toList();
                    UserUnionScuffleMemberWeek member = null;
                    if (!fightList.isEmpty()) { // 找出能打赢的战斗力最高的成员
                        member = fightList.stream().max(Comparator.comparingLong(UserUnionScuffleMemberWeek::getPower)).get();
                    } else { // 如果没有能打赢的成员，就随机选出一个
                        fightList = memberList.stream().filter(m -> !Tool.isInList(defeatMembersArray, m.getMemberId())).toList();
                        if (!fightList.isEmpty()) {
                            int index = Tool.getIntRandom(fightList.size());
                            member = fightList.get(index);
                        }
                    }
                    if (member == null) {
                        break;
                    }
                    boolean isWin = UnionScuffleManager.fight(userUnionScuffle, member, response);
                    if (isWin) {
                        userUnionScuffleInfo.addBeatNum(1);
                    }
                    UnionScuffleManager.subScore(userInfo, userUnion.getUnionId(), userUnionScuffle, userUnionScuffleInfo, curPower, member.getPower(), userUnionScuffleInfo.getEnemyUnionId());
                    hasFight = true;
                    UnionScuffleManager.updateAchieve(pbUserData, userInfo, userUnion.getUnionId(), 1);
                }
                if (hasFight) {
                    response.setTotalAddScore(userUnionScuffle.getSubScore());
                    UnionScuffleManager.endBattle(pbUserData, userInfo, userUnionScuffleInfo, userUnionScuffle, userUnion.getUnionId());
                    response.setIsEnd(1);
                    ProtoDataUtils.updatePBUserData(pbUserData, userUnionScuffle, true);
                }
//                ProtoDataUtils.updatePBUserData(pbUserData, userUnionScuffle, true);
                response.setMyPower(UnionScuffleManager.countPower(userUnionScuffle));
            }

        } catch (InvalidProtocolBufferException e) {
            return ErrorWord.PROTOCOL_PARSE_FAILED;
        } finally {// 释放锁
            MainService.releaseVertLock(lock);
        }
        return response;
    }

    // CMD_GAME_UNIONSCUFFLE_REPORT = 73405; // 乱斗战报
    public static Object CMD_GAME_UNIONSCUFFLE_REPORT(RequestParam clientParam) throws Exception {
        CSGameUnionscuffleReportRequest request = CSGameUnionscuffleReportRequest.parseFrom(clientParam.getData());
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        if (!FunctionManager.isFunctionClientOpen(FunctionManager.FUNCTION_ID_UNION_SCUFFLE, userInfo.getServerId())) {
            return ErrorWord.MODULE_LOCKED;
        }
//        long actId = request.getActId();
//        Act act = ActManager.getAct(actId);
//        if (act == null || !act.isStart(userInfo.getServerId()) || act.getType() != ActConstant.ACT_TYPE_UNION_SCUFFLE) {
//            return ErrorWord.NOT_DATA; // 活动未开始
//        }
        if (!UnionScuffleManager.isDuringGame()) {
            return ErrorWord.NOT_DATA; // 活动未开始
        }
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        if (userUnion.getUnionId() == 0) {
            return ErrorWord.MODULE_LOCKED; // 暂未开放
        }
        long memberCount = UnionManager.getUnionMemberNum(userUnion.getUnionId());
        if (memberCount < AllParam.UNION_SCUFFLE_MEMBER_LIMIT) {
            return ErrorWord.MODULE_LOCKED; // 人员数量不满足
        }

        CSGameUnionscuffleReportResponse.Builder response = CSGameUnionscuffleReportResponse.newBuilder();
        int type = request.getType();
        long lastReportId = request.getLastReportId();
        if (type == 1) { // 公告
            List<UnionScuffleNoticeWeek> noticeList = UnionScuffleManager.getUnionScuffleNoticeList();
            if (!noticeList.isEmpty()) {
                noticeList.sort(Comparator.comparing(UnionScuffleNoticeWeek::getId).reversed());
                for (UnionScuffleNoticeWeek unionScuffleNotice : noticeList) {
                    if (lastReportId > 0 && unionScuffleNotice.getId() <= lastReportId) { // 如果不是取全部公告，则在上一次取的公告位置截止
                        break;
                    }
                    if (!TimeUtils.isToday(unionScuffleNotice.getAddTime())) {
                        break;
                    }
                    response.addNoticeList(unionScuffleNotice.takeInitBuilder().build());
                }
            }
        } else {
            List<UnionScuffleReportWeek> reportList = UnionScuffleManager.getUnionScuffleReportList(userUnion.getUnionId());
            if (!reportList.isEmpty()) {
                Common.PBUserData.Builder pbUserData = response.getUserBuilder();
                reportList.sort(Comparator.comparing(UnionScuffleReportWeek::getId).reversed());
                for (UnionScuffleReportWeek unionScuffleReport : reportList) {
                    if (lastReportId > 0 && unionScuffleReport.getId() <= lastReportId) {
                        break;
                    }
                    if (!TimeUtils.isToday(unionScuffleReport.getAddTime())) {
                        break;
                    }
                    ProtoDataUtils.updatePBUserData(pbUserData, unionScuffleReport, true);
                }
            }
        }
        return response;
    }

    // CMD_GAME_UNIONSCUFFLE_WATCH_VIDEO = 73406; // 看广告
    public static Object CMD_GAME_UNIONSCUFFLE_WATCH_VIDEO(RequestParam clientParam) throws Exception {
        CSGameUnionscuffleWatchVideoRequest request = CSGameUnionscuffleWatchVideoRequest.parseFrom(clientParam.getData());
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        if (!FunctionManager.isFunctionClientOpen(FunctionManager.FUNCTION_ID_UNION_SCUFFLE, userInfo.getServerId())) {
            return ErrorWord.MODULE_LOCKED;
        }
//        long actId = request.getActId();
//        Act act = ActManager.getAct(actId);
//        if (act == null || !act.isGetRewardTime(userInfo.getServerId()) || act.getType() != ActConstant.ACT_TYPE_UNION_SCUFFLE) {
//            return ErrorWord.NOT_DATA; // 活动未开始
//        }

        if (!UnionScuffleManager.isDuringGame()) {
            return ErrorWord.NOT_DATA; // 活动未开始
        }
//        UserInfo userInfo = GameUser.getUserInfo(userId);
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        if (userUnion.getUnionId() == 0) {
            return ErrorWord.MODULE_LOCKED; // 暂未开放
        }
        long memberCount = UnionManager.getUnionMemberNum(userUnion.getUnionId());
        if (memberCount < AllParam.UNION_SCUFFLE_MEMBER_LIMIT) {
            return ErrorWord.INVALID_OPERATION; // 人员数量不满足
        }

        UserUnionScuffleInfoWeek userUnionScuffleInfo = UnionScuffleManager.getUserUnionScuffleInfo(userId);
        if (userUnionScuffleInfo.getVideoWatch() > 0) { // 每天只能看一次
            return ErrorWord.ALREADY_MAX;
        }

        CSGameUnionscuffleWatchVideoResponse.Builder response = CSGameUnionscuffleWatchVideoResponse.newBuilder();
        Common.PBUserData.Builder pbUserData = response.getUserBuilder();
        UserAdvideo userAdvideo = GameUser.getUserAdvideo(userId);
        userAdvideo.putAdStartTime(TimeUtils.getCurTime());
        String adcode = UUID.randomUUID().toString();//生成唯一码
        userAdvideo.putAdCode(adcode);
        userAdvideo.update();
        ProtoDataUtils.updatePBUserData(pbUserData, userAdvideo);
        return response;
    }

    // CMD_GAME_UNIONSCUFFLE_ADVIDEO_REWARD = 73407; // 广告恢复体力
    public static Object CMD_GAME_UNIONSCUFFLE_ADVIDEO_REWARD(RequestParam clientParam) throws Exception {
        long userId = clientParam.getUserId();
        CSGameUnionscuffleAdvideoRewardRequest request = CSGameUnionscuffleAdvideoRewardRequest.parseFrom(clientParam.getData());
        long curTime = TimeUtils.getCurTime();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        if (!FunctionManager.isFunctionClientOpen(FunctionManager.FUNCTION_ID_UNION_SCUFFLE, userInfo.getServerId())) {
            return ErrorWord.MODULE_LOCKED;
        }
//        long actId = request.getActId();
//        Act act = ActManager.getAct(actId);
//        if (act == null || !act.isGetRewardTime(userInfo.getServerId()) || act.getType() != ActConstant.ACT_TYPE_UNION_SCUFFLE) {
//            return ErrorWord.NOT_DATA; // 活动未开始
//        }

        if (!UnionScuffleManager.isDuringGame()) {
            return ErrorWord.NOT_DATA; // 活动未开始
        }
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        if (userUnion.getUnionId() == 0) {
            return ErrorWord.MODULE_LOCKED; // 暂未开放
        }
        long memberCount = UnionManager.getUnionMemberNum(userUnion.getUnionId());
        if (memberCount < AllParam.UNION_SCUFFLE_MEMBER_LIMIT) {
            return ErrorWord.MODULE_LOCKED; // 人员数量不满足
        }
        String adCode = request.getAdCode();
        UserAdvideo userAdvideo = GameUser.getUserAdvideo(userId);
        if (!GameUser.checkAdVideo(userAdvideo, adCode)) {// 观看时间不足，或是唯一码不对
            return ErrorWord.INVALID_OPERATION;
        }
        UserUnionScuffleInfoWeek userUnionScuffleInfo = UnionScuffleManager.getUserUnionScuffleInfo(userId);
        CSGameUnionscuffleAdvideoRewardResponse.Builder response = CSGameUnionscuffleAdvideoRewardResponse.newBuilder();
        Common.PBUserData.Builder pbUserData = response.getUserBuilder();
        userUnionScuffleInfo.addVideoWatch(1);
        userUnionScuffleInfo.addEnergy(userInfo, 1, LogType.UNION_SCUFFLE_ADVIDEO_RECOVER_ENERGY);
        userUnionScuffleInfo.update();
        ProtoDataUtils.updatePBUserData(pbUserData, userUnionScuffleInfo);
        userAdvideo.putAdCode("");
        userAdvideo.putAdStartTime(0);
        userAdvideo.update();
        ProtoDataUtils.updatePBUserData(pbUserData, userAdvideo);
        return response;
    }

    // CMD_GAME_UNIONSCUFFLE_REWARD = 73408; // 领取奖励
    public static Object CMD_GAME_UNIONSCUFFLE_REWARD(RequestParam clientParam) throws Exception {
        CSGameUnionscuffleRewardRequest request = CSGameUnionscuffleRewardRequest.parseFrom(clientParam.getData());
        long userId = clientParam.getUserId();
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        if (userUnion.getUnionId() == 0) {
            return ErrorWord.MODULE_LOCKED; // 暂未开放
        }
        UserInfo userInfo = GameUser.getUserInfo(userId);
        if (!FunctionManager.isFunctionClientOpen(FunctionManager.FUNCTION_ID_UNION_SCUFFLE, userInfo.getServerId())) {
            return ErrorWord.MODULE_LOCKED;
        }
//        long actId = request.getActId();
//        Act act = ActManager.getAct(actId);
//        if (act == null || !act.isStart(userInfo.getServerId()) || act.getType() != ActConstant.ACT_TYPE_UNION_SCUFFLE) {
//            return ErrorWord.NOT_DATA; // 活动未开始
//        }

        if (!UnionScuffleManager.isRewardTime()) {
            return ErrorWord.WRONG_STATUS; // 活动未开始
        }
        int rankId = request.getRankId();
        int myRank = 0;
        UserUnionScuffleInfoWeek userUnionScuffleInfo = UnionScuffleManager.getUserUnionScuffleInfo(userId);
        int serverGroup = ServerManager.getWarZoneId(userInfo.getServerId());
        // 判断要领取的是哪个排行榜
        if (rankId == RankConstant.ACTIVITY_CROSS_RANK_UNION_SCUFFLE_SINGLE) {
            if (userUnionScuffleInfo.getSingleRankReward() > 0) {
                return ErrorWord.ALREADY_MAX;
            }
            myRank = RankManager.getMyRank(rankId, serverGroup, userId, "0");
        } else if (rankId == RankConstant.ACTIVITY_CROSS_RANK_UNION_SCUFFLE) {
            if (userUnionScuffleInfo.getUnionRankReward() > 0) {
                return ErrorWord.ALREADY_MAX;
            }
            myRank = RankManager.getMyRank(rankId, serverGroup, userUnion.getUnionId(), "0");
        } else {
            return ErrorWord.BAD_PARAM;
        }

        if (myRank <= 0) {
            return ErrorWord.NOT_DATA_3; // 未上榜
        }
        // 根据排行榜类型查出名次并下发奖励
        RankReward rankReward = RankManager.getRankReward(rankId, myRank);
        if (rankReward == null) {
            return ErrorWord.NOT_DATA;
        }
        CSGameUnionscuffleRewardResponse.Builder response = CSGameUnionscuffleRewardResponse.newBuilder();
        Common.PBUserData.Builder pbUserData = response.getUserBuilder();
        RewardManager.addReward(userInfo, rankReward.getReward(), pbUserData, LogType.UNION_SCUFFLE_RANK_REWARD, rankId, myRank);
        // 将领奖标记存起来
        if (rankId == RankConstant.ACTIVITY_CROSS_RANK_UNION_SCUFFLE_SINGLE) {
            userUnionScuffleInfo.putSingleRankReward(rankReward.getId());
        } else {
            userUnionScuffleInfo.putUnionRankReward(rankReward.getId());
        }
        userUnionScuffleInfo.update();
        ProtoDataUtils.updatePBUserData(pbUserData, userUnionScuffleInfo);
        return response;
    }

    // CMD_GAME_UNIONSCUFFLE_BUY_GIFT = 73409; // 购买钻石礼包
    public static Object CMD_GAME_UNIONSCUFFLE_BUY_GIFT(RequestParam clientParam) throws Exception {
        long userId = clientParam.getUserId();
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        if (userUnion.getUnionId() == 0) {
            return ErrorWord.MODULE_LOCKED; // 暂未开放
        }
        CSGameUnionscuffleBuyGiftRequest request = CSGameUnionscuffleBuyGiftRequest.parseFrom(clientParam.getData());
        UserInfo userInfo = GameUser.getUserInfo(userId);
        if (!FunctionManager.isFunctionClientOpen(FunctionManager.FUNCTION_ID_UNION_SCUFFLE, userInfo.getServerId())) {
            return ErrorWord.MODULE_LOCKED;
        }
//        long actId = request.getActId();
//        Act act = ActManager.getAct(actId);
//        if (act == null || !act.isStart(userInfo.getServerId()) || act.getType() != ActConstant.ACT_TYPE_UNION_SCUFFLE) {
//            return ErrorWord.NOT_DATA; // 活动未开始
//        }

        if (!UnionScuffleManager.isDuringGame()) {
            return ErrorWord.NOT_DATA; // 活动未开始
        }
        int giftId = request.getGiftId();
        UnionScuffleGift gift = UnionScuffleUserData.getUnionScuffleGift(giftId);
        if (gift == null) {
            return ErrorWord.NOT_DATA_1; // 礼包不存在
        }
//        if (gift.getGroupId() != act.getActParamValue()) {
//            return ErrorWord.WRONG_STATUS;
//        }
        if (gift.getIapGiftId() > 0) { // 付费礼包
            return ErrorWord.INVALID_OPERATION;
        }
        int num = request.getNum();
        if (num < 1 || num > 999) {
            return ErrorWord.BAD_PARAM;
        }
        List<RewardItem> costItems = RewardManager.itemsToList(gift.getCost());
        if (num > 1) {
            for (RewardItem costItem : costItems) {
                costItem.setItemNum(costItem.getItemNum() * num);
            }
        }
        if (!BagManager.checkNeedItemNum(userInfo, costItems)) {
            return ErrorWord.ITEM_LACK; // 道具不够
        }
        CSGameUnionscuffleBuyGiftResponse.Builder response = CSGameUnionscuffleBuyGiftResponse.newBuilder();
        UserUnionScuffleGiftWeek userUnionScuffleGift = UnionScuffleUserData.getUserUnionScuffleGift(userId, gift.getId());
        if (userUnionScuffleGift == null) {
            userUnionScuffleGift = new UserUnionScuffleGiftWeek(userId, gift.getId());
            userUnionScuffleGift.doCreate();
        }
        if (userUnionScuffleGift.getBuyNum() + num > gift.getLimitCount()) {
            return ErrorWord.TIMES_LACK; // 购买次数已达上限
        }
        Common.PBUserData.Builder pbUserData = response.getUserBuilder();
        RewardManager.subReward(userInfo, costItems, pbUserData,LogType.UNION_SCUFFLE_GIFT_BUY, giftId);
        List<RewardItem> rewardItemList = RewardManager.itemsToList(gift.getReward());
        if (num > 1) {
            for (RewardItem rewardItem : rewardItemList) {
                rewardItem.setItemNum(rewardItem.getItemNum() * num);
            }
        }
        RewardManager.addReward(userInfo, rewardItemList, pbUserData,LogType.UNION_SCUFFLE_GIFT_BUY, giftId);
        userUnionScuffleGift.addBuyNum(num);
        userUnionScuffleGift.update();
        ProtoDataUtils.updatePBUserData(pbUserData, userUnionScuffleGift);
        return response;
    }

    // CMD_GAME_UNIONSCUFFLE_PASS_REWARD = 73410; // 领取通行证奖励
    public static Object CMD_GAME_UNIONSCUFFLE_PASS_REWARD(RequestParam clientParam) throws Exception {
        long userId = clientParam.getUserId();
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        if (userUnion.getUnionId() == 0) {
            return ErrorWord.MODULE_LOCKED; // 暂未开放
        }
        CSGameUnionscufflePassRewardRequest request = CSGameUnionscufflePassRewardRequest.parseFrom(clientParam.getData());
        UserInfo userInfo = GameUser.getUserInfo(userId);
        if (!FunctionManager.isFunctionClientOpen(FunctionManager.FUNCTION_ID_UNION_SCUFFLE, userInfo.getServerId())) {
            return ErrorWord.MODULE_LOCKED;
        }
//        long actId = request.getActId();
//        Act act = ActManager.getAct(actId);
//        if (act == null || !act.isStart(userInfo.getServerId()) || act.getType() != ActConstant.ACT_TYPE_UNION_SCUFFLE) {
//            return ErrorWord.NOT_DATA; // 活动未开始
//        }

        if (!UnionScuffleManager.isDuringGame()) {
            return ErrorWord.NOT_DATA; // 活动未开始
        }
        CSGameUnionscufflePassRewardResponse.Builder response = CSGameUnionscufflePassRewardResponse.newBuilder();
        Common.PBUserData.Builder pbUserData = response.getUserBuilder();
        UserUnionScuffleInfoWeek userUnionScuffleInfo = UnionScuffleManager.getUserUnionScuffleInfo(userId);
        int normalRewardId = userUnionScuffleInfo.getNormalPassReward();
        int highRewardId = userUnionScuffleInfo.getHighPassRewad();
        int specialRewardId = userUnionScuffleInfo.getSpecialPassReward();
        int beatNum = userUnionScuffleInfo.getBeatNum();
        List<UnionScufflePass> normalPassList = UnionScuffleUserData.getUnionScufflePassList(normalRewardId + 1);
        for (UnionScufflePass unionScufflePass : normalPassList) {
            if (unionScufflePass.getNum() > beatNum) {
                break;
            }
            RewardManager.addReward(userInfo, unionScufflePass.getNormalReward(), pbUserData, LogType.UNION_SCUFFLE_PASS_REWARD, unionScufflePass.getId(), 1);
            normalRewardId = unionScufflePass.getId();
        }
        if (userUnionScuffleInfo.getBuyHigh() == UserUnionScuffleInfo.YES) {
            List<UnionScufflePass> highPassList = UnionScuffleUserData.getUnionScufflePassList(highRewardId + 1);
            for (UnionScufflePass unionScufflePass : highPassList) {
                if (unionScufflePass.getNum() > beatNum) {
                    break;
                }
                RewardManager.addReward(userInfo, unionScufflePass.getHighReward(), pbUserData, LogType.UNION_SCUFFLE_PASS_REWARD, unionScufflePass.getId(), 2);
                highRewardId = unionScufflePass.getId();
            }
        }
        if (userUnionScuffleInfo.getBuySpecial() == UserUnionScuffleInfo.YES) {
            List<UnionScufflePass> specialPassList = UnionScuffleUserData.getUnionScufflePassList(specialRewardId + 1);
            for (UnionScufflePass unionScufflePass : specialPassList) {
                if (unionScufflePass.getNum() > beatNum) {
                    break;
                }
                RewardManager.addReward(userInfo, unionScufflePass.getSpecialReward(), pbUserData, LogType.UNION_SCUFFLE_PASS_REWARD, unionScufflePass.getId(), 3);
                specialRewardId = unionScufflePass.getId();
            }
        }
        if (normalRewardId == userUnionScuffleInfo.getNormalPassReward() && highRewardId == userUnionScuffleInfo.getHighPassRewad() && specialRewardId == userUnionScuffleInfo.getSpecialPassReward()) {
            return ErrorWord.ALREADY_MAX;
        }
        if (normalRewardId != userUnionScuffleInfo.getNormalPassReward()) {
            userUnionScuffleInfo.putNormalPassReward(normalRewardId);
        }
        if (highRewardId != userUnionScuffleInfo.getHighPassRewad()) {
            userUnionScuffleInfo.putHighPassRewad(highRewardId);
        }
        if (specialRewardId != userUnionScuffleInfo.getSpecialPassReward()) {
            userUnionScuffleInfo.putSpecialPassReward(specialRewardId);
        }
        userUnionScuffleInfo.update();
        ProtoDataUtils.updatePBUserData(pbUserData, userUnionScuffleInfo);

        return response;
    }

    // CMD_GAME_UNIONSCUFFLE_SHOP_BUY = 73411; // 商店兑换
    public static Object CMD_GAME_UNIONSCUFFLE_SHOP_BUY(RequestParam clientParam) throws Exception {
        long userId = clientParam.getUserId();
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        if (userUnion.getUnionId() == 0) {
            return ErrorWord.MODULE_LOCKED;
        }
        CSGameUnionscuffleShopBuyRequest request = CSGameUnionscuffleShopBuyRequest.parseFrom(clientParam.getData());
        UserInfo userInfo = GameUser.getUserInfo(userId);
        if (!FunctionManager.isFunctionClientOpen(FunctionManager.FUNCTION_ID_UNION_SCUFFLE, userInfo.getServerId())) {
            return ErrorWord.MODULE_LOCKED;
        }
//        long actId = request.getActId();
//        Act act = ActManager.getAct(actId);
//        if (act == null || !act.isStart(userInfo.getServerId()) || act.getType() != ActConstant.ACT_TYPE_UNION_SCUFFLE) {
//            return ErrorWord.NOT_DATA; // 活动未开始
//        }
        if (!UnionScuffleManager.isDuringGame() && !UnionScuffleManager.isRewardTime()) {
            return ErrorWord.NOT_DATA; // 活动未开始
        }
        int shopId = request.getShopId();
        int num = request.getNum();
        if (num < 1 || num > 999) {
            return ErrorWord.BAD_PARAM;
        }
        CSGameUnionscuffleShopBuyResponse.Builder response = CSGameUnionscuffleShopBuyResponse.newBuilder();
        Common.PBUserData.Builder pbUserData = response.getUserBuilder();
        Shop shop = ShopManager.getShop(shopId);
        if (shop == null || shop.getShopType() != ShopConstant.SHOP_TYPE_UNION_SCUFFLE) {
            return ErrorWord.NOT_DATA_1;
        }
        if (!ShopManager.checkShopUnlock(userInfo, shop)) {
            return ErrorWord.WRONG_STATUS;// 该商品尚未解锁,不能购买
        }
        List<RewardItem> costItem = CommonUtils.takeReawrdItemFromStr(shop.getPrice());
        CommonUtils.multipleItemList(costItem, num);//数量 x N倍
        if (shop.getIsFree() == 0 && !BagManager.checkNeedItemNum(userInfo, costItem)) {// 非免费商品
            return ErrorWord.ITEM_LACK;// 道具不足
        }
        UserUnionScuffleShopWeek userUnionScuffleShop = UnionScuffleUserData.getUserUnionScuffleShop(userId, shopId);
        if (userUnionScuffleShop == null) {
            userUnionScuffleShop = new UserUnionScuffleShopWeek(userId, shopId, 0);
            userUnionScuffleShop.doCreate();
        }
        if (!UnionScuffleManager.checkShopLimit(userUnionScuffleShop, shop, num)) {
            return ErrorWord.ALREADY_MAX;
        }
        RewardManager.subReward(userInfo, costItem, pbUserData, LogType.UNION_SCUFFLE_SHOP_BUY, shopId);
        List<RewardItem> rewardItemList = CommonUtils.takeReawrdItemFromStr(shop.getReward());
        CommonUtils.multipleItemList(rewardItemList, num);
        RewardManager.addReward(userInfo, rewardItemList, pbUserData, LogType.UNION_SCUFFLE_SHOP_BUY, shopId, num);
        if (shop.getLimitType() == ShopConstant.SHOP_LIMIT_TYPE_1) {
            userUnionScuffleShop.addDayBuyNum(num);
        } else {
            userUnionScuffleShop.addBuyNum(num);
        }
        userUnionScuffleShop.update();
        ProtoDataUtils.updatePBUserData(pbUserData, userUnionScuffleShop);
        return response;
    }


}
